<?php

namespace XWAM\Model;

/**
 * ProductCategory 模型类
 *
 * @since 1.0.0 <2016-5-28> SoChishun <14507247@qq.com> Added.
 */
class ProductCategoryModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 't_porg_product_category';

    /**
     * 是否批量验证
     * @var boolean
     */

    /**
     * 获取id_text列表
     * @param int $site_id
     * @param boolean $key_is_id
     * @return type
     * @since 1.0 2016-5-30 SoChishun Added.
     */
    public function getIdTextList($site_id, $key_is_id = false) {
        $list = array();
        if ($key_is_id) {
            $list = $this->where(array('site_id' => $site_id))->cache('productcategory_idtext_kvlist_' . $site_id, 10)->getField('id, title as text');
        } else {
            $list = $this->where(array('site_id' => $site_id))->cache('productcategory_idtext_list_' . $site_id, 10)->field('id, title as text')->select();
        }
        return $list;
    }

    /**
     * 当前分类以及所有子分类编号
     * @param type $id
     * @return type
     * @since 1.0 2016-8-25 SoChishun Added.
     */
    function getChildIds($id) {
        return $this->base_getChildIds($id);
    }

    /**
     * 当前分类以及所有父分类列表
     * @param type $id
     * @return type
     * @since 1.0 2016-8-25 SoChishun Added.
     */
    function getParentTree($id) {
        return $this->base_get_parent_list($id);
    }

    public function deleteCtegory($id = '') {
        if (!$id) {
            return $this->returnMsg(false, '参数无效');
        }
        // 判断是否有子项目
        $list = $this->query('select a.title from t_porg_product_category a inner join t_porg_product_category b on b.pid=a.id where b.pid in (' . $id . ')');
        $names = false;
        if ($list) {
            foreach ($list as $row) {
                $names .= ',' . $row['title'];
            }
        }
        if ($names) {
            return $this->returnMsg(false, '以下项目有子项目,请先转移子项目:' . "\n" . ltrim($names, ','));
        }
        // 判断是否有引用
        $category_ids = $this->table('t_porg_product_goods')->where(array('category_id' => array('in', $id)))->getField('category_id', true);
        if ($category_ids) {
            $names = $this->where(array('id' => array('in', $category_ids)))->getField('title', true);
            return $this->returnMsg(false, '以下项目已被占用,无法删除:' . "\n" . implode(',', $names));
        }
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    /**
     * 
     * @param type $selectOption
     * @param type $dataOption
     * @return type
     */
    function selectTree($selectOption = array(), $dataOption = array()) {
        $selectOption = array_merge(array('field' => 'id, title, pid, code, sort, status, create_time', 'order' => 'sort, id'), $selectOption);
        return $this->baseSelectTree($selectOption, $dataOption);
    }

    /**
     * 获取层级列表
     * @param type $select_options
     * @param type $data_options
     * @return type
     */
    function selectTreex($select_options = array(), $data_options = array(), $site_id = 0) {
        $select_options = array_merge(array('field' => 'id, title, code, pid, brand_id, specification_ids, sort, status, create_time', 'order' => 'sort, id'), $select_options);
        $list = $this->baseSelectTree($select_options, $data_options);
        if (!$list || !$site_id) {
            return $list;
        }
        // 获取品牌名称
        $m_brand = new ProductBrandModel();
        $brands = $m_brand->getIdTextList($site_id, true);
        unset($m_brand);
        // 获取规格名称
        $m_spec = new ProductSpecificationModel();
        $spes = $m_spec->getIdTextList($site_id, true);
        unset($m_spec);
        $aout = array();
        $aout2 = array();
        $aout3 = array();
        foreach ($list as $row) {
            if ($row['children']) {
                $aout2 = array();
                foreach ($row['children'] as $row2) {
                    if ($row2['children']) {
                        $aout3 = array();
                        foreach ($row2['children'] as $row3) {
                            $aout3[] = $this->set_field_text($row3, $brands, $spes);
                        }
                        $row2['children'] = $aout3;
                    }
                    $aout2[] = $this->set_field_text($row2, $brands, $spes);
                }
                $row['children'] = $aout2;
            }
            $aout[] = $this->set_field_text($row, $brands, $spes);
        }
        return $aout;
    }

    function set_field_text($row, $brands, $spes) {
        $row['brand_text'] = $brands && !empty($row['brand_id']) && array_key_exists($row['brand_id'], $brands) ? $brands[$row['brand_id']] : '';
        $row['specification_text'] = '';
        if ($spes && !empty($row['specification_ids'])) {
            $aspetext = array();
            $aspeids = explode(',', $row['specification_ids']);
            foreach ($aspeids as $speid) {
                if (array_key_exists($speid, $spes)) {
                    $aspetext[] = $spes[$speid];
                }
            }
            $row['specification_text'] = implode(' | ', $aspetext);
        }
        return $row;
    }

    /**
     * 
     * @param type $select_options
     * @param type $data_options
     * @return type
     */
    function selectTreeJson($select_options = array(), $data_options = array()) {
        $select_options = array_merge(array('field' => 'id, title as text', 'order' => 'sort, id'), $select_options);
        return $this->baseSelectTree($select_options, $data_options);
    }

    function saveCategory() {
        $rules = array(
            array('title', 'require', '名称无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        if (empty($this->pid)) {
            unset($this->data['pid']);
        }
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    /**
     * 复制类别
     * @return type
     * @since 1.0 <2016-1-14> SoChishun Added.
     */
    function copyCategory($id) {
        $table = $this->tableName;
        $this->execute("insert into $table (title, pid, status, site_id) select concat(title,'_new'), pid, status, site_id from $table where id=$id");
        return $this->returnMsg(true);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    /**
     * 批量更新外键对应的标题
     * @param type $all
     * @since 1.0 2017-3-17 SoChishun Added.
     */
    static function updateForeignTitle($all = false, $id = '') {
        M()->execute("update t_porg_product_goods a left join t_porg_product_category c on a.category_id=c.id set a.category_title=c.title where " . ($id ? "a.category_id in ($id)" : "a.category_id > 0") . ($all || $id ? '' : " and a.category_title=''"));
    }

}
